<?php 
	/*
	 * ThinkSAAS核心函数
	 * @copyright (c) ThinkSAAS All Rights Reserved
	 * @version 0.6
	 * @code by QINIAO
	 * @Email:qiniao@vip.qq.com
	 * @TIME:2010-12-18
	 */
	 
	/*
	 *系统消息
	 */
	 
	function qiMsg($msg,$button='点击返回>>',$url='javascript:history.back(-1);', $isAutoGo=false){
		echo 
<<<EOT
<html>
<head>
EOT;
		if($isAutoGo){
			echo "<meta http-equiv=\"refresh\" content=\"2;url=$url\" />";
		}
		echo 
<<<EOT
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ThinkSAAS 提示</title>
<style type="text/css">
<!--
body {
background-color:#D6E9A0;
font-family: Arial;
font-size: 12px;
line-height:150%;
text-align:center;
}
a{color:#555555;}
.main {
width:500px;
background-color:#FFFFFF;
font-size: 12px;
color: #666666;
margin:100px auto 0;
list-style:none;
padding:20px;
}
.main p {
line-height: 18px;
margin: 5px 20px;
font-size:14px;
}
-->
</style>
</head>
<body>
<div class="main">
<p>$msg</p>
<p><a href="$url">$button</a></p>
</div>
</body>
</html>
EOT;
		exit;
	}

	
	/*
	 * 分页函数
	 *
	 * @param int $count 条目总数
	 * @param int $perlogs 每页显示条数目
	 * @param int $page 当前页码
	 * @param string $url 页码的地址
	 * @return unknown
	 */
	 
	function pagination($count,$perlogs,$page,$url){
		$pnums = @ceil($count / $perlogs);
		$re = '';
		for ($i = $page-5;$i <= $page+5 && $i <= $pnums; $i++){
			if ($i > 0){
				if ($i == $page){
					$re .= " <span class='current'>$i</span> ";
				} else {
					$re .= " <a href=\"$url=$i\">$i</a> ";
				}
			}
		}
		if ($page > 6) $re = "<a href=\"$url=1\" title=\"首页\">&laquo;</a> ...$re";
		if ($page + 5 < $pnums) $re .= "... <a href=\"$url=$pnums\" title=\"尾页\">&raquo;</a>";
		if ($pnums <= 1) $re = '';
		return $re;
	}
	
	/*
	 *验证Email
	 */
	function valid_email($email){
		if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)){ 
			return false; 
		}
		$email_array		= explode("@", $email); 
		$local_array		= explode(".", $email_array[0]); 
		for ($i = 0; $i < sizeof($local_array); $i++){ 
			if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])){ 
				return false; 
			 } 
		}   
		if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])){
			$domain_array = explode(".", $email_array[1]); 
			if (sizeof($domain_array) < 2){ 
				return false;
			} 
			for ($i = 0; $i < sizeof($domain_array); $i++){ 
				if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])){ 
					return false; 
				} 
			} 
		} 
		return true;
	} 

	/*
	 *处理时间的函数
	 */	
	 
	function getTime($btime, $etime){
	
		if ($btime < $etime) {
			$stime = $btime;
			$endtime = $etime;
		}else {
			$stime = $etime;
			$endtime = $btime;
		}
		$timec = $endtime - $stime;
		$days = intval($timec / 86400);
		$rtime = $timec % 86400;
		$hours = intval($rtime / 3600);
		$rtime = $rtime % 3600;
		$mins = intval($rtime / 60);
		$secs = $rtime % 60;
		if($days>=1){
			return $days.' 天前';
		}
		if($hours>=1){
			return $hours.' 小时前';
		}

		if($mins>=1){
			return $mins.' 分钟前';
		}
		if($secs>=1){
			return $secs.' 秒前';
		}
	 
	}
	
	/*
	 *获取用户IP
	 */
	 
	function getIp(){
	
		if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')){
			$PHP_IP = getenv('HTTP_CLIENT_IP');
		}elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')){
			$PHP_IP = getenv('HTTP_X_FORWARDED_FOR');
		}elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')){
			$PHP_IP = getenv('REMOTE_ADDR');
		}elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')){
			$PHP_IP = $_SERVER['REMOTE_ADDR'];
		}
		preg_match("/[\d\.]{7,15}/", $PHP_IP, $ipmatches);
		$PHP_IP = $ipmatches[0] ? $ipmatches[0] : 'unknown';
		return $PHP_IP;
	}
	
	/*
	 *图片采集函数
	 *By QINIAO 2010-09-13
	 */
	
	function getImg($url,$filepath,$filename=""){ 

		if($url==""):return false;endif;

		$ext=strrchr($url,"."); 
		
		if($filename==""){ 
		
			if($ext!=".gif" && $ext!=".jpg"):return false;endif; 

			$filename=date("dmyhis").$ext; 

		}else{
		
			$filename=$filename.$ext; 
			
		}
		
		//判断路径是否存在
		!is_dir($filepath)?mkdir($filepath):null; 

		ob_start(); 
		
		readfile($url); 
		
		$img = ob_get_contents(); 
		
		ob_end_clean(); 
		
		$size = strlen($img);
		
		//指定打开的文件
		$fp2 = @fopen($filepath.'/'.$filename, 'a');
		
		fwrite($fp2,$img); 
		
		fclose($fp2);

		return $filename; 
	}
	
	/*
	 *过滤脚本代码
	 */
	 
	function cleanJs($text){
		$text = trim ( $text );
		$text = stripslashes ( $text );
		//完全过滤注释
		$text = preg_replace ( '/<!--?.*-->/', '', $text );
		//完全过滤动态代码
		$text = preg_replace ( '/<\?|\?>/', '', $text );
		//完全过滤js
		$text = preg_replace ( '/<script?.*\/script>/', '', $text );
		//过滤多余html
		$text = preg_replace ( '/<\/?(html|head|meta|link|base|body|title|style|script|form|iframe|frame|frameset)[^><]*>/i', '', $text );
		//过滤on事件lang js
		while ( preg_match ( '/(<[^><]+)(lang|onfinish|onmouse|onexit|onerror|onclick|onkey|onload|onchange|onfocus|onblur)[^><]+/i', $text, $mat ) ){
			$text = str_replace ( $mat [0], $mat [1], $text );
			}
		while ( preg_match ( '/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i', $text, $mat ) ){
			$text = str_replace ( $mat [0], $mat [1] . $mat [3], $text );
			}
		//彻底过滤空格BY QINIAO
		$text = preg_replace('/\s(?=\s)/', '', $text);
		$text = preg_replace('/[\n\r\t]/', ' ', $text);
		$text = str_replace ( '  ', ' ', $text );
		$text = str_replace ( ' ', '', $text );
		$text = str_replace ( '&nbsp;', '', $text );
		return $text;
	}
	
	/*
	 *纯文本输出
	 */
	 
	function t($text){
		$text = cleanJs ( $text );
		$text = strip_tags ( $text );
		$text = htmlspecialchars ( $text );
		return $text;
	}
	
	/*
	 * 输出安全的html
	 */
	 
	function h($text){
		$text = cleanJs ( $text );
		return $text;
	}
	
	
	/*
	 *反序列化为UTF-8
	 */

	function mb_unserialize($serial_str) {
		$serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
		$serial_str= str_replace("\r", "", $serial_str);      
		return unserialize($serial_str);
	}

	/*
	 *反序列化为ASC
	 */

	function asc_unserialize($serial_str) {

		$serial_str = preg_replace('!s:(\d+):"(.*?)";!se', '"s:".strlen("$2").":\"$2\";"', $serial_str );
		$serial_str= str_replace("\r", "", $serial_str);      
		return unserialize($serial_str);

	}
	
	/*
	 *utf-8截取
	 */
	 
	function getsubstrutf8($string, $start = 0,$sublen,$append=true){
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all($pa, $string, $t_string);
		if(count($t_string[0]) - $start > $sublen && $append==true){
			return join('', array_slice($t_string[0], $start, $sublen))."...";
		}else{
			return join('', array_slice($t_string[0], $start, $sublen));
		}
	}
	
	/*
	 *读取目录列表函数
	 * dirs,files
	 */
	
	function dirList($dir, $bool = "dirs"){
	
	   $truedir = $dir; //注意：确定路劲是否带有'/'
	   
	   $dir = scandir($dir);
	   if($bool == "files"){
			$direct = 'is_dir';
	   }elseif($bool == "dirs"){
			$direct = 'is_file';
	   }
	   
	   foreach($dir as $k => $v){
			if(($direct($truedir.'/'.$dir[$k])) || $dir[$k] == '.' || $dir[$k] == '..' ){
				unset($dir[$k]);
			}
	   }
	   $dir = array_values($dir);
	   return $dir;
	}
	
	/*
	 * 计算时间
	 */
	 
	function getmicrotime(){ 
		list($usec, $sec) = explode(" ",microtime()); 
		return ((float)$usec + (float)$sec); 
	}
	
	/*
	 *写入APP缓存
	 */
	 
	function AppCacheWrite($cacheData,$app,$cacheFile){
		
		$appFile = THINKROOT.'/data/cache/'.$app;
		
		if(!is_dir($appFile)) @mkdir($appFile, 0777); 
		
		$cacheFile = $appFile.'/'.$cacheFile;
		
		@ $fp = fopen($cacheFile,'wb') OR qiMsg('读取缓存失败。如果您使用的是Unix/Linux主机，请修改缓存目录 (data/cache/'.$app.') 下所有文件的权限为777。如果您使用的是Windows主机，请联系管理员，将该目录下所有文件设为everyone可写');
		@ $fw = fwrite($fp,$cacheData) OR qiMsg('写入缓存失败，缓存目录 (data/cache/'.$app.') 不可写');
		fclose($fp);
	}
	
	/*
	 *读取APP缓存
	 */
	 
	function AppCacheRead($app,$cacheFile){
		$cacheFile = THINKROOT.'/data/cache/'.$app.'/'.$cacheFile;
		if(@$fp = fopen($cacheFile,'r')){
			$data = fread($fp,filesize($cacheFile));
			fclose($fp);
		}
		return unserialize($data);
	}
	
	/*
	 * 把数组转换为,号分割的字符串
	 */
	 
	function array_to_str($arr) {
		$str = '';
		$count = 1;
		foreach ($arr as $a) {
			if ($count==1) {
				$str .= $a;
			} else {
				$str .= ','.$a;
			}
				$count++;
		}
		return $str;
	}